﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TemplateWeb.Models;
using TemplateWeb.Helpers;
using TemplateWeb.ShoppingCartModule;
using TemplateWeb.Models.ViewModels;
using System.Web.Security;

namespace TemplateWeb.Controllers
{
    public class HomeController : BaseController
    {
        public ActionResult Index()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_INDEX
            };
            return View(CreateViewModel(data));
        }

        public ActionResult TinTuc(int idloaitintuc = -1)
        {
            if (idloaitintuc == -1)
            {
                idloaitintuc = _repLoaiTinTuc.SelectAll().First().ID;
            }
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_TINTUC,
                IDLoaiTinTuc = idloaitintuc
            };
            return View(CreateViewModel(data));
        }

        public ActionResult ChiTietTinTuc(int id)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_CHITIETTINTUC,
                IntID = id
            };
            return View(CreateViewModel(data));
        }

        public ActionResult GocChiaSe()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_GOCCHIASE
            };
            return View(CreateViewModel(data));
        }

        public ActionResult GioiThieu()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_INDEX
            };
            return View(CreateViewModel(data));
        }

        public ActionResult DoiTac()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_DOITAC
            };
            return View(CreateViewModel(data));
        }

        public ActionResult ChiTietDoiTac(int id)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_CHITIETDOITAC,
                IntID = id
            };
            return View(CreateViewModel(data));
        }

        public ActionResult LienHe()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_INDEX
            };
            return View(CreateViewModel(data));
        }

        public ActionResult Sach(int idloaisach = -1)
        {
            if (idloaisach == -1)
            {
                idloaisach = _repLoaiSach.SelectAll().First().ID;
            }
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_SACH,
                IDLoaiSach = idloaisach
            };
            return View(CreateViewModel(data));
        }

        public ActionResult ChiTietSach(int id)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_CHITIETSACH,
                IntID = id
            };
            return View(CreateViewModel(data));
        }

        public ActionResult ChiTietGocChiaSe(int id)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_CHITIETGOCCHIASE,
                IntID = id
            };
            return View(CreateViewModel(data));
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult InsertHopThu(FormCollection forms)
        {
            string hoten = forms.GetValues("HopThu_HoTen")[0];
            string email = forms.GetValues("HopThu_Email")[0];
            string tieude = forms.GetValues("HopThu_TieuDe")[0];
            string noidung = forms.GetValues("HopThu_NoiDung")[0];

            var newItem = new HopThu
            {
                EmailNguoiHoi = email,
                TieuDe = tieude,
                NoiDung = noidung,
                NgayHoi = DateTime.Now,
                DaPhanHoi = false,
                HoTen = hoten
            };
            var result = _repHopThu.Insert(newItem);
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_INDEX
            };
            ViewData["HoiDap"] = result ? "Thư của bạn đã được gửi đi, sau khi xem xét chúng tôi sẽ gửi phản hồi cho bạn!" : "Thư của bạn chưa được gửi đi, có lỗi sảy ra trong quá trình gửi câu hỏi.";
            return View("LienHe", CreateViewModel(data));
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult InsertDanhGia(FormCollection forms)
        {
            string idsach = forms.GetValues("DanhGia_IDSach")[0];
            if (forms.GetValues("DanhGia_Diem") == null)
            {
                return RedirectToAction("ChiTietSach", new { id = int.Parse(idsach) });
            }
            string diem = forms.GetValues("DanhGia_Diem")[0];
            var newItem = new DanhGia
            {
                IDSach = int.Parse(idsach),
                Diem = int.Parse(diem)
            };
            var result = _repDanhGia.Insert(newItem);
            return RedirectToAction("ChiTietSach", new { id = int.Parse(idsach) });
        }

        public ActionResult Login(string error = "")
        {
            if (!error.Equals(string.Empty))
            {
                ViewData["error"] = error;
            }
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_REGISTER
            };
            return View(CreateViewModel(data));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ThemBaiChiaSe()
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_THEMCHIASE
            };
            ViewData["ThemBaiChiaSe"] = null;
            return View(CreateViewModel(data));
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult InsertGocChiaSe(FormCollection forms)
        {
            string tieude = forms.GetValues("GocChiaSe_TieuDe")[0];
            string noidung = forms.GetValues("GocChiaSe_NoiDung")[0];
            string noidungrutgon = StringHelper.Truncate(forms.GetValues("GocChiaSe_NoiDungRutGon")[0], WebConfiguration.GocChiaSeSortDescription);
            var file = Request.Files["GocChiaSe_HinhMinhHoa"];
            string refName = "";
            var newItem = new GocChiaSe
            {
                TieuDe = tieude,
                NoiDung = noidung,
                NoiDungRutGon = noidungrutgon,
                HinhMinhHoa = "noimages.jpg",
                NgayDang = DateTime.Now,
                TenNguoiChiaSe = forms.GetValues("GocChiaSe_TenNguoiChiaSe")[0],
                DaDuyet = false
            };
            var result = _repGocChiaSe.Insert(newItem);
            if (result)
            {
                if (file.ContentLength != 0)
                {
                    result = UploadFile(file, "/Content/Images/Items/", newItem.ID.ToString(), ref refName);
                    if (result)
                    {
                        var addedItem = _repGocChiaSe.SelectByID(newItem.ID);
                        addedItem.HinhMinhHoa = refName;
                        _repGocChiaSe.Save();
                    }
                }
            }

            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_THEMCHIASE
            };
            ViewData["ThemBaiChiaSe"] = "Bài chia sẻ của bạn đã được gửi đi, sau khi xem xét nội dung, chúng tôi sẽ đăng bài của bạn";
            return View("ThemBaiChiaSe", CreateViewModel(data));
        }

        ////////////////////// SHOPPING CART ////////////////////////
        public ActionResult AddToCart(int id, int idloaisach, int num = 0)
        {
            // Retrieve the food from the database 
            var addedItem = _repSach.SelectByID(id);

            // Add it to the shopping cart 
            var cart = ShoppingCart.GetCart(this.HttpContext);
            if (num == 0)
            {
                cart.AddToCart(addedItem);
            }
            else
            {
                cart.AddToCart(addedItem, num);
            }

            // Go back to the main store page for more shopping 
            // Set up our ViewModel 
            return RedirectToAction("Sach", new { idloaisach = idloaisach });
        }

        [HttpPost]
        public ActionResult RemoveFromCart(int id)
        {
            // Remove the item from the cart 
            var cart = ShoppingCart.GetCart(this.HttpContext);

            // Get the name of the food to display confirmation 
            string foodName = _repSach.SelectByID(_repCart.SelectByRecordID(id).SachID.Value).TenSach;

            // Remove from cart 
            cart.RemoveFromCart(id);

            // Display the confirmation message 
            var results = new GioHangRemoveViewModel
            {
                Message = Server.HtmlEncode(foodName) +
                    " has been removed from your shopping cart.",
                CartTotal = cart.GetTotal(),
                ItemCount = 0,
                DeleteId = id
            };

            return Json(results);
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Approve(FormCollection forms)
        {
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_ORDER
            };

            var groupViewModel = CreateViewModel(data);
            string username = string.Empty;

            // Redirect to 
            if (!User.Identity.IsAuthenticated)
            {
                return View("Login", groupViewModel);
            }

            return View("ApproveOrder", groupViewModel);
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AddOrder(FormCollection forms)
        {
            string chuthich = forms.GetValues("Order_ChuThich")[0];
            string diachinguoinhan = forms.GetValues("Order_DiaChiNguoiNhan")[0];
            string phonenguoinhan = forms.GetValues("Order_SoDienThoaiNguoiNhan")[0];
            string tennguoinhan = forms.GetValues("Order_TenNguoiNhan")[0];
            string sotaikhoan = forms.GetValues("Order_SoTaiKhoan")[0];
            string mabaomat = forms.GetValues("Order_MaBaoMat")[0];
            var tongtien = decimal.Parse(forms.GetValues("Order_TongTien")[0]);
            
            // First checking whether account is valid
            var changeMsg = string.Empty;
            var changeResult = SEBankingService.Instance.ExChangeVND(sotaikhoan, mabaomat, WebConfiguration.AccountNumber, tongtien);
            switch (changeResult)
            {
                case 1:
                    changeMsg = "Exchange succeeded";
                    break;

                case 0:
                    changeMsg = "the number of money is not match";
                    break;

                case -1:
                    changeMsg = "id of source card do not exist";
                    break;

                case -2:
                    changeMsg = "source card is not enought money";
                    break;

                case -3:
                    changeMsg = "Security code do not match";
                    break;

                case -4:
                    changeMsg = "id of target card do not match";
                    break;
            }

            DataTransferViewModel data = null;

            if (changeResult == 1)
            {
                // Then insert new order
                var newOrder = new DonDatHang
                {
                    IDUser = Guid.Parse(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString()),
                    NgayDatHang = DateTime.Now,
                    DaXacNhan = false,
                    DaGiaoHang = false,
                    HuyDonHang = false,
                    ChuThich = chuthich,
                    DiaChiNguoiNhan = diachinguoinhan,
                    SoDienThoaiNguoiNhan = phonenguoinhan,
                    TenNguoiNhan = tennguoinhan
                };

                var result = _repDonDatHang.Insert(newOrder);

                if (result)
                {
                    // Next insert order details
                    var cart = ShoppingCart.GetCart(this.HttpContext);
                    foreach (var item in cart.GetCartItems())
                    {
                        var itemBuy = _repSach.SelectByID(item.SachID.Value);
                        var orderDetail = new ChiTietDonDatHang
                        {
                            IDDonDatHang = newOrder.ID,
                            IDSach = item.SachID,
                            SoLuong = item.Count,
                            Gia = itemBuy.Gia
                        };
                        result = _repChiTietDonDatHang.Insert(orderDetail);
                    }
                    cart.EmptyCart();
                }

                data = new DataTransferViewModel
                {
                    EnumViewModelType = EnumViewModel.HOME_ORDERHISTORY,
                    GuidID = newOrder.IDUser.Value
                };
                ViewData["OrderResult"] = "Đặt hàng thành công! chúng tôi sẽ xử lý đơn hàng trong thời gian sớm nhất có thể";
                return View("OrdersHistory", CreateViewModel(data));
            }
            else
            {
                data = new DataTransferViewModel
                {
                    EnumViewModelType = EnumViewModel.HOME_ORDER
                };
                ViewData["ChangeMsg"] = changeMsg;
                ViewData["Order_TenNguoiNhan"] = tennguoinhan;
                ViewData["Order_DiaChiNguoiNhan"] = diachinguoinhan;
                ViewData["Order_SoDienThoaiNguoiNhan"] = phonenguoinhan;
                ViewData["Order_ChuThich"] = chuthich;
                ViewData["Order_MaBaoMat"] = mabaomat;
                ViewData["Order_SoTaiKhoan"] = sotaikhoan;
                var groupViewModel = CreateViewModel(data);
                return View("ApproveOrder", groupViewModel);
            }            
        }

        public ActionResult OrdersHistory(string username)
        {
            var iduser = _repNguoiDung.SelectByUserName(username).BaseInfo.ID;
            var data = new DataTransferViewModel
            {
                EnumViewModelType = EnumViewModel.HOME_ORDERHISTORY,
                GuidID = iduser
            };
            return View(CreateViewModel(data));
        }

        public ActionResult SelectOrderDetailByIDOrder(Guid iduser, int idorder)
        {
            var data = new DataTransferViewModel
            {
                GuidID = iduser,
                IDDonDatHang = idorder,
                EnumViewModelType = EnumViewModel.HOME_ORDERHISTORY_ORDERDETAIL,
            };
            return View("OrdersHistory", CreateViewModel(data));
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult TimKiem(FormCollection forms)
        {
            var tensach = forms.GetValues("txtTimKiemTenSach")[0];
            var tentacgia = forms.GetValues("txtTimKiemTenTacGia")[0];

            var data = new DataTransferViewModel
            {
                TimKiem_TenSach = tensach,
                TimKiem_TenTacGia = tentacgia,
                EnumViewModelType = EnumViewModel.HOME_TIMKIEM,
            };
            return View("KetQuaTimKiem", CreateViewModel(data));
        }

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UserCancelOrder(FormCollection forms)
        {
            var iduser = Guid.Parse(forms.GetValues("Orders_IDUser")[0]);
            var idorder = int.Parse(forms.GetValues("Orders_ID")[0]);
            var orders = _repDonDatHang.SelectByID(idorder);
            orders.HuyDonHang = true;

            var result = _repDonDatHang.Save();

            var data = new DataTransferViewModel
            {
                GuidID = iduser,
                IDDonDatHang = idorder,
                EnumViewModelType = EnumViewModel.HOME_ORDERHISTORY_ORDERDETAIL,
            };
            ViewData["XacNhanHuyMsg"] = "Xác nhận đơn hàng của bạn đã được hủy"; 
            return View("OrdersHistory", CreateViewModel(data));
        }
    }
}

